const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isWXWork: app.isWXWork,
    tagGroup: [],
    customTags: [],
    tagDialogVisible: false,
    tagName: '',
    tagHistory: [],
    isLoaded: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({ title: '编辑标签' });
    const { openid, customerOpenid } = options;
    this.setData({ openid, customerOpenid }, () => {
      this.initTagData();
      this.getTagHistory();
    });
  },

  initTagData() {
    Promise.all([
      this.getTagList(),
      this.getSelectedTags(),
    ]).then(([tagList, selectedTags]) => {
      const tagGroup = (tagList.qy || []).map(v => ({
        ...v,
        tags: v.tags.map(tag => ({
            ...tag,
          active: selectedTags.indexOf(tag.tag_name) > -1,
        })),
      }));
      const customTags = (tagList.person || [])
        .map(v => ({
          ...v,
          active: v.status == 1,
        }));
      this.setData({
        tagGroup,
        customTags,
        originalTagJsonStr: this.getTagJsonStr(tagGroup, customTags),
        isLoaded: true,
      });
    });
  },

  getTagHistory() {
    app.util.request({
      url: 'card/api/usedDiyTag',
      data: {
        openid: this.data.openid,
        client_openid: this.data.customerOpenid,
      },
      success: res => {
        if (res.data && res.data.errno === 0) {
          const data = res.data.data;
          this.setData({ tagHistory: data.sort((a, b) => b.orderby - a.orderby) });
        }
      },
    });
  },

  getTagList() {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'card/api/qyTagList',
        data: {
          openid: this.data.openid,
          client_openid: this.data.customerOpenid,
        },
        showLoading: true,
        success: res => {
          if (res.data && res.data.errno === 0) {
            const data = res.data.data;
            resolve(data);
          } else {
            reject(res);
          }
        },
        fail: err => {
          reject(err);
        },
      });
    });
  },

  getSelectedTags() {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'card/api/personalTag',
        data: {
          openid: this.data.openid,
          client_openid: this.data.customerOpenid,
        },
        showLoading: true,
        success: res => {
          if (res.data && res.data.errno === 0) {
            const data = res.data.data;
            resolve(data.new || []);
          } else {
            reject(res);
          }
        },
        fail: err => {
          reject(err);
        },
      });
    });
  },

  tagTapped(e) {
    const { index, groupIndex } = e.currentTarget.dataset;
    const active = this.data.tagGroup[groupIndex].tags[index].active;
    this.setData({
      [`tagGroup[${groupIndex}].tags[${index}].active`]: !active,
    });
  },

  customTagTapped(e) {
    const { index, id } = e.currentTarget.dataset;
    const active = this.data.customTags[index].active;
    this.setData({
      [`customTags[${index}].active`]: !active,
    });
    app.util.request({
      url: 'card/api/personalTagChoose',
      data: {
        openid: this.data.openid,
        client_openid: this.data.customerOpenid,
        tagId: id,
        status: active ? '1' : '2',
      },
      success: res => {
      },
    });
  },

  showTagDialog() {
    this.setData({
      tagDialogVisible: true,
      tagName: '',
    });
  },

  tagChanged(e) {
    const { value } = e.detail;
    this.setData({
      tagName: value,
    });
  },

  closeTagDialog() {
    this.setData({
      tagDialogVisible: false,
      tagName: '',
    });
  },

  addCustomTag() {
    if (!this.data.tagName) {
      wx.showToast({
        title: '标签内容不能为空',
        icon: 'none',
      });
      return;
    }
    app.util.request({
      url: 'card/api/personalTagWrite',
      data: {
        openid: this.data.openid,
        client_openid: this.data.customerOpenid,
        tagname: this.data.tagName,
      },
      success: res => {
        if (res.data && res.data.errno === 0) {
          const customTags = this.data.customTags;
          customTags.push({
            id: res.data.data,
            status: '1',
            active: true,
            tagname: this.data.tagName,
          });
          this.setData({ customTags });
          this.closeTagDialog();
        }
      },
    });
  },

  selectCustomTag(e) {
    const { name } = e.currentTarget.dataset;
    this.setData({ tagName: name }, () => {
      this.addCustomTag();
    });
  },

  getTagJsonStr(tagGroup, customTags) {
    const tagData = {};
    let selectedTags = [];
    for (let i = 0; i < tagGroup.length; i++) {
      const group = tagGroup[i];
      selectedTags = selectedTags.concat(group.tags.filter(v => v.active));
    }
    selectedTags.forEach((tag, index) => {
      tagData[`${index}`] = {
        id: tag.id,
        group_id: tag.group_id,
        tag_id: tag.tag_id,
        tag_name: tag.tag_name,
      };
    });
    tagData.diy = customTags.filter(v => v.active).map(v => v.tagname);
    return JSON.stringify(tagData);
  },

  saveTags() {
    const tagJsonStr = this.getTagJsonStr(this.data.tagGroup, this.data.customTags);
    if (this.data.originalTagJsonStr === tagJsonStr) {
      wx.navigateBack();
    } else {
      // wx.showToast({
      //   title: '添加成功',
      //   icon: 'success',
      // });
      // setTimeout(() => {
      //   wx.navigateBack();
      // }, 1000)
      app.util.request({
        url: 'card/api/personalTagSave',
        data: {
          openid: this.data.openid,
          client_openid: this.data.customerOpenid,
          tagJsonStr,
        },
        method: 'POST',
        success: res => {
          if (res.data && res.data.errno === 0) {
            wx.showToast({
              title: '添加成功',
              icon: 'success',
            });
            setTimeout(() => {
              wx.navigateBack();
            }, 1000)
          }
        },
      });
    }
  },
});
